package com.changgou.oauth.service.impl;

import com.changgou.oauth.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 密码模式登录实现
     * @param username
     * @param password
     * @param grant_type
     * @param clientId
     * @param clientSecret
     */
    @Override
    public ResponseEntity<Map> login(String username, String password, String grant_type, String clientId, String clientSecret) throws Exception {

        ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");

        //获取指定服务的注册信息
        String url = serviceInstance.getUri()+"/oauth/token";

        /**
         * 封装参数
         */
        MultiValueMap<String, String> parameterMap = new LinkedMultiValueMap<>();
        parameterMap.add("username",username);
        parameterMap.add("password",password);
        parameterMap.add("grant_type",grant_type);

        /**
         * 封装头信息
         */
        MultiValueMap<String, String> headerMap = new LinkedMultiValueMap<>();
        headerMap.add("Authorization","Basic "+new String((Base64.getEncoder().encode((clientId+":"+clientSecret).getBytes())),"UTF-8"));

        HttpEntity httpEntity = new HttpEntity(parameterMap,headerMap);

        /**
         * 1:请求地址
         * 2:提交方式
         * 3:requestEntity:请求提交的数据信息封装请求体|请求头
         * 4:responseType:返回数据需要转换的类型
         */
        //待用请求地址  http://localhost:9001/oauth/token
        ResponseEntity<Map> entity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Map.class);
        System.out.println(entity.getBody());
        return entity;
    }
}
